<template>
  <n-grid cols="2 s:2 m:2 l:3 xl:3 2xl:3" responsive="screen">
    <n-grid-item>

      <n-list>
        <n-list-item>
          <template #suffix>
            <n-button type="primary" text @click="modelDetails.show=true; modelDetails.type=1">修改</n-button>
          </template>
          <n-thing title="账户密码">
            <template #description>
              <span class="text-gray-400">密码设置需要较高复杂度会更安全！</span>
            </template>
          </n-thing>
        </n-list-item>
        <n-list-item>
          <template #suffix>
            <n-button type="primary" :loading="emailBindBtnLoading" text v-throttle="bindOrUnbindBtnHandler">
              {{ userStore.info?.email ? '解绑' : '绑定' }}
            </n-button>
          </template>
          <n-thing title="绑定邮箱">
            <template #description>
              <span class="text-gray-400">
                {{ userStore.info?.email ? `已绑定邮箱: ${userStore.info.email}` : `绑定邮箱使得账号更安全！` }}
              </span>
            </template>
          </n-thing>
        </n-list-item>
        <n-list-item>
          <template #suffix>
            <n-button type="primary" :loading="wxBtnLoading" text v-throttle="wxBindOrUnbindBtnHandler">
              {{ userStore.info?.bindWx ? '解绑' : '绑定' }}
            </n-button>
          </template>
          <n-thing title="绑定微信">
            <template #description>
              <span class="text-gray-400">
                {{ userStore.info?.bindWx ? `已绑定微信` : `绑定微信使得登录更快捷！` }}
              </span>
            </template>
          </n-thing>
        </n-list-item>
        <n-list-item>
          <template #suffix>
            <n-button type="primary" text @click="message.info('暂未实现，敬请期待!')">绑定</n-button>
          </template>
          <n-thing title="绑定手机">
            <template #description>
              <span class="text-gray-400">
                {{ userStore.info?.telephone ? `已绑定手机: ${userStore.info.telephone}` : `绑定手机使得账号更安全！` }}
              </span>
            </template>
          </n-thing>
        </n-list-item>
      </n-list>

      <n-modal
        v-model:show="modelDetails.show"
        style="width: 300px"
        preset="card"
        :title="modelDetails.title[modelDetails.type-1]"
        size="medium"
        :bordered="false"
        :on-after-leave="modelAfterLeaveHandler"
      >
        <!-- 修改密码 -->
        <n-form :label-width="80" v-if="modelDetails.type === 1"
                :model="updatePwdFormValue" :rules="updatePwdRules" ref="updatePwdFormRef">
          <n-form-item label="旧密码" path="oldPassword">
            <n-input
              v-model:value="updatePwdFormValue.oldPassword"
              type="password"
              showPasswordOn="click"
              placeholder="请输入旧密码"
            >
              <template #prefix>
                <n-icon size="18" color="#808695">
                  <LockClosedOutline />
                </n-icon>
              </template>
            </n-input>
          </n-form-item>

          <n-form-item label="新密码" path="newPassword">
            <n-input
              v-model:value="updatePwdFormValue.newPassword"
              type="password"
              showPasswordOn="click"
              placeholder="请输入新密码"
            >
              <template #prefix>
                <n-icon size="18" color="#808695">
                  <LockClosedOutline />
                </n-icon>
              </template>
            </n-input>
          </n-form-item>

          <n-form-item label="确认密码" path="checkPassword">
            <n-input
              v-model:value="updatePwdFormValue.checkPassword"
              type="password"
              showPasswordOn="click"
              placeholder="请再次输入密码"
            >
              <template #prefix>
                <n-icon size="18" color="#808695">
                  <LockClosedOutline />
                </n-icon>
              </template>
            </n-input>
          </n-form-item>

          <n-space justify="center">
            <n-button type="primary" @click="updatePwdSubmit">修改密码</n-button>
          </n-space>
        </n-form>

        <!-- 绑定邮箱 -->
        <n-form :label-width="80" v-if="modelDetails.type === 2"
                :show-label="false"
                :model="bindEmailFormValue" :rules="bindEmailRules" ref="bindEmailFormRef">
          <n-form-item label="邮箱" path="email">
            <n-input
              v-model:value="bindEmailFormValue.email"
              type="email"
              showPasswordOn="click"
              placeholder="请输入邮箱"
              @keyup.enter="bindEmailSubmit"
            >
              <template #prefix>
                <n-icon size="18" color="#808695">
                  <Mail />
                </n-icon>
              </template>
            </n-input>
          </n-form-item>

          <n-space justify="center">
            <n-button type="primary" :loading="emailBindBtnLoading" v-throttle="bindEmailSubmit">绑定邮箱</n-button>
          </n-space>
        </n-form>

        <!-- 绑定手机 -->
      </n-modal>
    </n-grid-item>
  </n-grid>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue';
import { useMessage } from 'naive-ui';
import {changePassword, reqBindEmail, reqUnbindEmail} from '@/api/authority/user'
import { LockClosedOutline, Mail } from '@vicons/ionicons5';
import { FormItemRule } from 'naive-ui';
import { useUserStore } from "@/store/modules/user";
import { useRouter, useRoute } from "vue-router";
import { useWxOauth, WxOauthBusinessConstant } from "@/hooks/useWxOauth";

const router = useRouter()
const route = useRoute()
const userStore = useUserStore()
const message = useMessage();

// 模态框展示不同类型的表单,其中
// 1 -> 密码修改
// 2 -> 邮箱绑定
// 3 -> 手机绑定
const modelDetails = reactive({
  show: false,
  type: 1,
  title: ['密码修改', '邮箱绑定', '手机绑定']
})
// 模态框关闭回调
const modelAfterLeaveHandler = () => {
  // 清空对应表单的数据
  if (modelDetails.type === 1) {
    updatePwdFormValue.oldPassword = updatePwdFormValue.newPassword = updatePwdFormValue.checkPassword = ''
  }
  else if (modelDetails.type === 2) {
    bindEmailFormValue.email = ''
  }
  else if (modelDetails.type === 3) {

  }
}

/** 修改密码的模态框 */
const updatePwdFormRef: any = ref(null);
const updatePwdFormValue = reactive({
  oldPassword: '',
  newPassword: '',
  checkPassword: '',
});
// 密码校验规则
const validatePasswordStartWith = (
  rule: FormItemRule,
  value: string
): boolean => {
  return (
    !!updatePwdFormValue.newPassword &&
    updatePwdFormValue.newPassword.startsWith(value) &&
    updatePwdFormValue.newPassword.length >= value.length
  )
}
function validatePasswordSame (rule: FormItemRule, value: string): boolean {
  return value === updatePwdFormValue.newPassword
}
const updatePwdRules = {
  oldPassword: {
    required: true,
    message: '请输入旧密码',
    trigger: 'blur',
  },
  newPassword: {
    required: true,
    message: '请输入新密码',
    trigger: 'blur',
  },
  checkPassword: [
    {
      required: true,
      message: '请再次输入密码',
      trigger: ['input', 'blur']
    },
    {
      validator: validatePasswordStartWith,
      message: '两次密码输入不一致',
      trigger: 'input'
    },
    {
      validator: validatePasswordSame,
      message: '两次密码输入不一致',
      trigger: ['blur', 'password-input']
    }
  ],
};
function updatePwdSubmit() {
  updatePwdFormRef.value.validate(async (errors) => {
    if (!errors) {
      // 如果新旧密码一致那就提醒
      if (updatePwdFormValue.oldPassword === updatePwdFormValue.newPassword) {
        return message.warning('新旧密码一致，请重新设置新密码')
      }
      await changePassword({
        oldPassword: updatePwdFormValue.oldPassword,
        newPassword: updatePwdFormValue.newPassword
      })
      // 重新登陆
      await userStore.logout();
    } else {
      message.error('验证失败，请填写完整信息');
    }
  });
}


/** 绑定邮箱的模态框 */
const bindEmailFormRef: any = ref(null);
const bindEmailFormValue = reactive({
  email: ''
});
const bindEmailRules = {
  email: {
    required: true,
    message: '请输入邮箱',
    trigger: 'blur',
  },
};
const emailBindBtnLoading = ref(false)
const bindOrUnbindBtnHandler = async () => {
  emailBindBtnLoading.value = true;
  try {
    if (userStore.info?.email) {
      await reqUnbindEmail().catch(e => {
        if (e.message === '未绑定邮箱') {
          userStore.refreshUserInfo()
        }
      });
    } else {
      modelDetails.show = true;
      modelDetails.type = 2;
    }
  } finally {
    emailBindBtnLoading.value = false;
  }
}
function bindEmailSubmit() {
  if (emailBindBtnLoading.value) return;
  bindEmailFormRef.value.validate(async (errors) => {
    emailBindBtnLoading.value = true;
    if (!errors) {
      await reqBindEmail(bindEmailFormValue.email)
        .catch(e => {
          if (e.message === '您已绑定邮箱') {
            userStore.refreshUserInfo()
          }
        })
        .finally(() => modelDetails.show = false)
    } else {
      message.error('验证失败，请填写完整信息');
    }
    emailBindBtnLoading.value = false;
  });
}

/** 微信绑定 */
const { handlerWxOauth } = useWxOauth()
const wxBtnLoading = ref(false)
const wxBindOrUnbindBtnHandler = async () => {
  wxBtnLoading.value = true
  try {
    await handlerWxOauth(
      userStore.info?.bindWx ? WxOauthBusinessConstant.UNBIND : WxOauthBusinessConstant.BIND,
      () => {
        message.success(userStore.info?.bindWx ? '微信解绑成功' : '微信绑定成功')
        userStore.setUserInfo({
          ...userStore.info,
          bindWx: !userStore.info?.bindWx
        })
      }
    )
  } finally {
    wxBtnLoading.value = false
  }
}

/** 绑定手机的模态框 */



</script>
